﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using PccCommonForC;

public partial class Shopping_Stall_Stall_v1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ViewState["dtBasket"] = (DataTable)Session["dtBasket"];

            string ActivePage = Request.QueryString["ActivePage"];
            if (Request.QueryString["PageSize"] != "" && Request.QueryString["PageSize"] != null)
            {
                int iPageSize = int.Parse(Request.QueryString["PageSize"]);
                if (iPageSize > 100)
                    iPageSize = 100;
                txtPageSize.Text = iPageSize.ToString();
            }
            else
            {
                string PageSize = ConfigurationManager.AppSettings["PageSizeViewThumbnail"];
                txtPageSize.Text = PageSize;
            }

            if (ActivePage == null || ActivePage == "")
            {
                PagingProduct(0);
            }
            else
            {
                PagingProduct(int.Parse(ActivePage));
                lblindex.Text = ActivePage;
            }
        }
    }


    private void PagingProduct(int index)
    {
        clsWebShop cls = new clsWebShop();
        clsCommon clsC = new clsCommon();

        PccMsg msg = new PccMsg();
        msg.CreateFirstNode("TopicID", clsC.ConvertToDecimal(cls.killSQLInjection(Request.QueryString["TopicID"])).ToString());
        msg.CreateFirstNode("CatID", clsC.ConvertToDecimal(cls.killSQLInjection(Request.QueryString["CatID"])).ToString());
        msg.CreateFirstNode("PdName", cls.killSQLInjection(Request.QueryString["PdName"]));
        msg.CreateFirstNode("CatName", cls.killSQLInjection(Request.QueryString["CatName"]));
        msg.CreateFirstNode("TopicName", cls.killSQLInjection(Request.QueryString["TopicName"]));
        msg.CreateFirstNode("StartRecord", index.ToString());
        msg.CreateFirstNode("PageSize", txtPageSize.Text);

        DataSet ds = null;
        ds = cls.Get_ProductByCondition_Paging(msg.GetXmlStr);
        DataTable dtPD = new DataTable();
        DataTable dtCount = new DataTable();

        dtPD = ds.Tables["ProductList"];
        dtCount = ds.Tables["TCounts"];
        if (dtCount.Rows.Count <= 0)
        {
            pnControl.Visible = false;

        }
        else
        {
            if (int.Parse(dtCount.Rows[0]["Counts"].ToString()) > int.Parse(txtPageSize.Text)) //Neu lon hon page size hien Moving Control 
            {
                pnControl.Visible = true;
                lblrecordcount.Text = dtCount.Rows[0]["Counts"].ToString();
                DisplayControlPaging(index);
            }
            else
            {
                pnControl.Visible = false;
                lblrecordcount.Text = dtCount.Rows[0]["Counts"].ToString();
            }
        }

        if (dtPD.Rows.Count > 0)
        {
            if (Request.QueryString["kind"] != "search")
            {
                lblKind.Text = dtPD.Rows[0]["TopicName"].ToString();
            }
            else
            {
                lblKind.Text = "<font size='2pt'>Những sản phẩm tìm được</font>";
            }
        }
        else
        {
            lblEmpty.Visible = true;
        }

        dtlThumbnail.RepeatColumns = int.Parse(ConfigurationManager.AppSettings["RepeatColumnThumnail"]);
        dtlThumbnail.DataSource = dtPD;
        dtlThumbnail.DataBind();

        if (dtlThumbnail.Items.Count > 0)
        {
            for (int i = 0; i < dtlThumbnail.Items.Count; i++)
            {
                if (i + 1 % 3 == 0)
                {
                    HtmlTableCell td_right = (HtmlTableCell)dtlThumbnail.Items[i].FindControl("td_right");
                    td_right.Visible = false;
                }
                if (i == 0 || i == 1 || i == 2)
                {
                    HtmlTableCell td_top = (HtmlTableCell)dtlThumbnail.Items[i].FindControl("td_top");
                    td_top.Visible = true;
                }

            }
        }
    }
    private void DisplayControlPaging(int index)
    {
        lblDisplay.Text = "Số mẩu tin: <b>" + lblrecordcount.Text;
        lblDisplay.Text += "</b> | Trang: <b> ";
        int Display = index / int.Parse(txtPageSize.Text) + 1;
        lblDisplay.Text += Display.ToString();
        lblDisplay.Text += " </b> trên tổng số <b>";
        if (int.Parse(lblrecordcount.Text) % int.Parse(txtPageSize.Text) > 0)
        {
            Display = int.Parse(lblrecordcount.Text) / int.Parse(txtPageSize.Text) + 1;
            lblDisplay.Text += Display.ToString();
        }
        else
        {
            Display = int.Parse(lblrecordcount.Text) / int.Parse(txtPageSize.Text);
            lblDisplay.Text += Display.ToString();
        }

        lblDisplay.Text += " </b> trang";
    }


    protected void dtlThumbnail_ItemDataBound(object sender, DataListItemEventArgs e)
    {

        e.Item.Attributes.Add("onmouseover", "this.style.backgroundImage=url('../../Images/Body/bgButton.png')");
        e.Item.Attributes.Add("onmouseout", "this.style.backgroundImage=url('');");
        /*Image imgProductStall = (Image)e.Item.FindControl("imgProductStall");
        if (DataBinder.Eval(e.Item.DataItem, "ImgUrl").ToString() == "" || DataBinder.Eval(e.Item.DataItem, "ImgUrl") == null)
            imgProductStall.ImageUrl = "~/Images/Body/Noimages.gif";
        else
            imgProductStall.ImageUrl = "~/" + DataBinder.Eval(e.Item.DataItem, "ImgUrl");*/

        string img = ResolveUrl("~/") + DataBinder.Eval(e.Item.DataItem, "ImgUrl").ToString();
        if (DataBinder.Eval(e.Item.DataItem, "ImgUrl").ToString() == "" || DataBinder.Eval(e.Item.DataItem, "ImgUrl") == null)
            img = ResolveUrl("~/") + "Images/Body/Noimages.gif";


        string HTML = "";

        HTML += "<a href='" + img + "'  class='customGal' title='" + DataBinder.Eval(e.Item.DataItem, "PDName").ToString() + "'>";
        HTML += "<img  src='" + img + "'  alt='' title='Click to enlarge' border='0'  class='img_Product' >";
        HTML += "</a>";

        Literal ltlImages = (Literal)e.Item.FindControl("ltlImages");
        ltlImages.Text = HTML;

        Image imgHot = (Image)e.Item.FindControl("imgHot");
        if (DataBinder.Eval(e.Item.DataItem, "IsHot").ToString() == "Y")
        {
            imgHot.Visible = true;
            imgHot.ImageUrl = "~/Images/Icon/hot.gif";
        }
        if (DataBinder.Eval(e.Item.DataItem, "KindNo").ToString() == "F")
        {
            Panel pnlKindNo = (Panel)e.Item.FindControl("pnlKindNo");
            pnlKindNo.Visible = false;
        }

        ImageButton btnISelect = (ImageButton)e.Item.FindControl("btnISelect");
        ImageButton btnICancel = (ImageButton)e.Item.FindControl("btnICancel");
        ImageButton btnIDetail = (ImageButton)e.Item.FindControl("btnIDetail");

        Label lblDongia = (Label)e.Item.FindControl("lblDongia");
        lblDongia.Text = FormatMoney(lblDongia.Text);

        string Price = DataBinder.Eval(e.Item.DataItem, "Price").ToString();
        string Rate = DataBinder.Eval(e.Item.DataItem, "Rate").ToString();

        HtmlTableCell tdPrice = (HtmlTableCell)e.Item.FindControl("tdPrice");
        if (DataBinder.Eval(e.Item.DataItem, "IsSaleOf").ToString() == "Y")
        {
            HtmlTableRow trSaleOf = (HtmlTableRow)e.Item.FindControl("trSaleOf");
            trSaleOf.Visible = true;

            Label lblDiscountPrice = (Label)e.Item.FindControl("lblDiscountPrice");
            lblDiscountPrice.Text = FormatMoney(lblDiscountPrice.Text);

            tdPrice.Attributes.Add("class", "td_linethrought");
            //get price discount
            Price = DataBinder.Eval(e.Item.DataItem, "DiscountPrice").ToString();
            Rate = DataBinder.Eval(e.Item.DataItem, "DiscountRate").ToString();
        }
        if (DataBinder.Eval(e.Item.DataItem, "Status").ToString() == "C")
        {
            tdPrice.Attributes.Add("class", "td_linethrought");
        }



        bool flag = true;
        if (Session["dtBasket"] != null)
        {
            DataTable dtBasket = (DataTable)Session["dtBasket"];
            clsCommon clsCom = new clsCommon();
            if (clsCom.SearchDataTable(dtBasket, "PDID", DataBinder.Eval(e.Item.DataItem, "PDID").ToString()) != -1) //Neu ton tai san pham nay hien nut cancel
            {
                flag = false;
                btnISelect.Visible = false;
                btnICancel.Visible = true;
                btnICancel.CommandName = "CancelBasket";
                btnICancel.CommandArgument = DataBinder.Eval(e.Item.DataItem, "PDID").ToString();

            }
        }
        if (flag == true)
        {
            btnISelect.CommandName = "AddBasket";
            btnISelect.CommandArgument = DataBinder.Eval(e.Item.DataItem, "PDID").ToString() + "☼" + DataBinder.Eval(e.Item.DataItem, "PDName").ToString() + "☼" + Price + "☼" + Rate + "☼" + DataBinder.Eval(e.Item.DataItem, "KindNo").ToString();
        }
        btnIDetail.CommandName = "DetailBasket";
        btnIDetail.CommandArgument = DataBinder.Eval(e.Item.DataItem, "PDID").ToString();

    }

    protected void dtlThumbnail_ItemCommand(object source, DataListCommandEventArgs e)
    {

        DataTable dtBasket = new DataTable();

        if (Session["dtBasket"] != null)
        {
            dtBasket = (DataTable)Session["dtBasket"];
        }
        else
        {
            dtBasket.Columns.Add("PDID");
            dtBasket.Columns.Add("PDNAME");
            dtBasket.Columns.Add("PRICE");
            dtBasket.Columns.Add("QUANTITY");
            dtBasket.Columns.Add("RATE");
            dtBasket.Columns.Add("KINDNO");
        }

        if (e.CommandName.ToLower() == "addbasket")
        {
            string[] strArgument = e.CommandArgument.ToString().Split('☼');
            string strPDID = strArgument[0];
            string strPDName = strArgument[1];
            string strPDPrice = strArgument[2];
            string strPDRate = strArgument[3];
            string strPDKindNo = strArgument[4];

            clsWebShop cls = new clsWebShop();
            cls.UpdateViewCount(strPDID);

            DataRow row = dtBasket.NewRow();
            row["PDID"] = strPDID;
            row["PDNAME"] = strPDName;
            row["PRICE"] = strPDPrice;
            row["QUANTITY"] = "1";
            row["RATE"] = strPDRate;
            row["KINDNO"] = strPDKindNo;
            dtBasket.Rows.Add(row);

            Session["dtBasket"] = dtBasket;
            string url = "Stall.aspx?" + ReturnQueryString("TopicID") + "&ActivePage=" + lblindex.Text + "&PageSize=" + txtPageSize.Text + "&" + ReturnQueryString("CatID") + "&#PageIndex_" + strPDID;

            Response.Redirect(url);


        }
        else if (e.CommandName.ToLower() == "cancelbasket")
        {
            string PDID = e.CommandArgument.ToString();

            int index = SearchDataTable(dtBasket, "PDID", PDID);

            if (index != -1)
            {
                dtBasket.Rows[index].Delete();
                string url = "Stall.aspx?" + ReturnQueryString("TopicID") + "&ActivePage=" + lblindex.Text + "&PageSize=" + txtPageSize.Text + "&" + ReturnQueryString("CatID") + "&#PageIndex_" + PDID;
                Response.Redirect(url);
            }
        }
        else if (e.CommandName.ToLower() == "detailbasket")
        {
            string PDID = e.CommandArgument.ToString();
            Response.Redirect("ProductDetail.aspx?PDID=" + PDID);
        }
        PagingProduct(int.Parse(lblindex.Text));

    }



    #region "CommonFunction"
    private int SearchDataTable(DataTable dt, string Col, string value)
    {
        int index = -1;

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            if (dt.Rows[i][Col].ToString() == value)
            {
                index = i;
                break;
            }
        }
        return index;
    }
    private string ReturnQueryString(string strQuery)
    {
        string str = "";
        if (Request.QueryString[strQuery] != null && Request.QueryString[strQuery] != "")
        {
            str = strQuery + "=" + Request.QueryString[strQuery];
        }
        return str;
    }

    private string FormatMoney(string sNum)
    {
        string sReturn = "0";
        try
        {
            sReturn = string.Format("{0:###,###,##0}", decimal.Parse(sNum));
        }
        catch (Exception) { }
        return sReturn;
    }


    private string FormatMoney(decimal dNum)
    {
        string sReturn = "0";
        try
        {
            sReturn = string.Format("{0:###,###,##0}", dNum);
        }
        catch (Exception) { }
        return sReturn;
    }
    #endregion

    #region "Event"
    protected void btnINext_Click(object sender, ImageClickEventArgs e)
    {
        int index = int.Parse(lblindex.Text) + int.Parse(txtPageSize.Text);
        if (index < int.Parse(lblrecordcount.Text))
        {
            PagingProduct(index);
            lblindex.Text = index.ToString();
        }
    }
    protected void btnIPre_Click(object sender, ImageClickEventArgs e)
    {
        int index = int.Parse(lblindex.Text) - int.Parse(txtPageSize.Text);
        if (index < 0)
            index = 0;

        PagingProduct(index);
        lblindex.Text = index.ToString();
    }
    protected void btnILast_Click(object sender, ImageClickEventArgs e)
    {

        int iMod = int.Parse(lblrecordcount.Text) % int.Parse(txtPageSize.Text);
        int index;
        if (iMod > 0)
            index = int.Parse(lblrecordcount.Text) - iMod;
        else
            index = int.Parse(lblrecordcount.Text) - int.Parse(txtPageSize.Text);

        PagingProduct(index);
        lblindex.Text = index.ToString();
    }
    protected void btnIFirst_Click(object sender, ImageClickEventArgs e)
    {
        int index = 0;
        PagingProduct(index);
        lblindex.Text = index.ToString();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (int.Parse(txtPageSize.Text) > 100)
            txtPageSize.Text = "100";
        PagingProduct(0);
    }
    #endregion
}
